package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    @Transactional
    public void add(List<OrderSetting> orderSettingList) {
        log.debug("OrderSettingServiceImpl: add: orderSettingList ===> " + orderSettingList);
        if (orderSettingList!=null && orderSettingList.size()>0){
            for (OrderSetting orderSetting : orderSettingList) {
                addOrEdit(orderSetting);
            }
        }
    }

    @Override
    public List<OrderSetting> findByDate(String date) {
        log.debug("OrderSettingServiceImpl: findByDate: date ===> " + date);
        String thisMonthFirstDay = date + "-01";
        String thisMonthLastDay = getThisMonthLastDay(thisMonthFirstDay);
        List<OrderSetting> orderSettingList = orderSettingDao.findByMonth(thisMonthFirstDay,thisMonthLastDay);
        log.debug("OrderSettingServiceImpl: findByDate: orderSettingList ===> " + orderSettingList);
        return orderSettingList;
    }

    private String getThisMonthLastDay(String thisMonthFirstDay){
        log.debug("OrderSettingServiceImpl: getThisMonthLastDay: thisMonthFirstDay ===> " + thisMonthFirstDay);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date first = dateFormat.parse(thisMonthFirstDay);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(first);
            calendar.add(Calendar.MONTH,1);
            calendar.add(Calendar.DAY_OF_MONTH,-1);

            String last = dateFormat.format(calendar.getTime());
            return last;
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    @Transactional
    public void addOrEdit(OrderSetting orderSetting) {
        log.debug("OrderSettingServiceImpl: saveOrEdit: orderSetting ===> " + orderSetting);
        OrderSetting orderSettingDb = orderSettingDao.findByDate(orderSetting.getOrderDate());
        if (orderSettingDb == null){
            orderSettingDao.add(orderSetting);
        }else {
            if (orderSettingDb.getReservations()>orderSetting.getNumber()){
                throw new RuntimeException("已预约人数大于可预约人数,设置失败");
            }else {
                orderSettingDao.edit(orderSetting);
            }
        }
    }
}
